package com.yc.jpyy.facecheck.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yc.jpyy.base.bean.Client;
import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.config.Config;
import com.yc.jpyy.base.controller.BaseController;
import com.yc.jpyy.base.service.BaseService;
import com.yc.jpyy.mobile.dao.BizDao;
import com.yc.jpyy.mobile.dao.TeacherDao;
import com.yc.jpyy.mobile.service.BizService;
import com.yc.jpyy.mobile.service.TeacherService;

@Controller
@RequestMapping(value = "/facecheck")
public class NewLoginAndOutController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(NewLoginAndOutController.class);
	
	@Autowired
	private  BizService bizService;	  
	
	@Autowired
	private  BizDao bizDao;
	
	@Autowired
	private TeacherService teacherService;
	
	@Autowired
	private  TeacherDao teacherDao;
	
	public  static String uri = Config.getCompareQRCodeUrl();
	WebSocketContainer container = ContainerProvider.getWebSocketContainer();
	Client client = new Client();
    Session session = null;
	/**
	 * 登录/登出确认通知
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/SigninConfirm", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String signinConfirm(HttpServletRequest request)
			throws UnsupportedEncodingException {
		logger.info("signinConfirm：登录登出开始-------------*********");
		RestResponse response = new RestResponse();
		request.setCharacterEncoding("UTF-8");

		try {
			// 教练/学员全国编号
			String ObjectNum = request.getParameter("ObjectNum");
			// 终端编号
			String Devnum = request.getParameter("Devnum");
			// 请求对象类型
			String Type = request.getParameter("Type");
			// 事件类型
			String EventType = request.getParameter("EventType");
			//身份证UID
			String UID = request.getParameter("UID");	
			/*String result = requestCompareQRCode(response,ObjectNum,Type,EventType);
			System.out.print(result);*/
			if(ObjectNum != null && !ObjectNum.isEmpty()
					&& Type != null && !Type.isEmpty()
					&& EventType != null && !EventType.isEmpty()){	
				String remindString ="身份证信息和登录信息不符，请检查！";
				if(null != UID && !UID.isEmpty()){
					//type=1教练；type=2学员
					if(Integer.parseInt(Type) == 1){
						//防止第一个人刷身份证刷出二维码，却是另外一个人扫了二维码
						//根据ObjectNum获取教练的UId
						String coachUID = teacherDao.getUIDForFaceCheck(ObjectNum);
						//如果教练的UId存在且不为空(第一次登陆才传身份证号，这时库里教练的身份证是不存在的，如果存在则提示身份标识已存在)
						if(null != coachUID && !coachUID.equals("")){
							 response.setErrorcode(1);
							 response.setMessage(remindString);
						}else{
							 //查询该UID是否存在（除了ObjectNum对应的记录，其他记录里是否存在该UID）
						     int uIdCount = teacherDao.isExistUIDForFaceCheck(UID);
						     //如果存在则提示身份标识已存在
							 if(uIdCount > 0){
								 response.setErrorcode(1);
								 response.setMessage(remindString);
							 }else{
								 //第一次登陆，如果库里不存在，则把身份证号更新进去（以后登录不会再传身份证号）
								 teacherDao.updateUIDForFaceCheck(UID, ObjectNum); 
								 //验证设备编号(VehicleId和gpsId)并访问二维码比对接口
								 checkDevNum(response,Devnum,ObjectNum,Type,EventType);
							 }
						}
					}else if(Integer.parseInt(Type)==2){
						//学员同教练原理一样
						String stuUID = bizDao.getUIDForFaceCheck(ObjectNum);
						if(null != stuUID && !stuUID.equals("")){
							 response.setErrorcode(1);
							 response.setMessage(remindString);
						}else{
						     int uIdCount = bizDao.isExistUIDForFaceCheck(UID);
							 if(uIdCount > 0){
								 response.setErrorcode(1);
								 response.setMessage(remindString);
							 }else{
								 bizDao.updateUIDForFaceCheck(UID, ObjectNum);
								 //验证设备编号
								 checkDevNum(response,Devnum,ObjectNum,Type,EventType);
							 }
						}
					}
				}else{
					//不是第一次登录（扫码），则直接验证设备编号
					checkDevNum(response,Devnum,ObjectNum,Type,EventType);
				}
			}else{
				response.setErrorcode(1);
				response.setMessage("必填字段为空...");
			}		    
		} catch (Exception e) {
			logger.info("signinConfirm："+ e.toString());
			response.setErrorcode(1);
			response.setMessage("访问失败，请稍候重试！");
		} finally {
			logger.info("signinConfirm：登录登出结束-------------*********");
			return response.toJSON();
		}
	}
	
	   //验证设备编号(VehicleId和gpsId)
		public void checkDevNum(RestResponse response, String Devnum, String ObjectNum, String Type, String EventType)throws Exception{
			//根据设备编号查VehicleId
			Integer VehicleId = bizService.getVehicleIdForFaceCheck(Devnum);
			if(null != VehicleId && VehicleId != 0){
				/*//根据设备编号查GpsId
				Integer gpsId = bizService.getGpsIdForFaceCheck(VehicleId);
				if( null != gpsId){*/
					//二维码比对
					String result = requestCompareQRCode(response,ObjectNum,Type,EventType,Devnum);
					if(result.equals("0")){
						response.setErrorcode(0);
						response.setMessage("操作成功");
					}else if(result.equals("1")){
						response.setErrorcode(1);
						response.setMessage("操作失败");
					}
			   /* }else{
				   response.setErrorcode(1);
				   response.setMessage("计时终端不存在");
			    }*/
			}else{
				response.setErrorcode(1);
				response.setMessage("终端信息不存在！");	
			}
		}
		
		//二维码比对访问外部接口
		public String requestCompareQRCode (RestResponse response,String ObjectNum, String Type, String EventType,String Devnum) throws Exception{
			String url = Config.getChekUrl();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair number = new BasicNameValuePair("number", ObjectNum);
			NameValuePair type = new BasicNameValuePair("type", Type);
			NameValuePair eventType = new BasicNameValuePair("eventType", EventType);
			NameValuePair simCard = new BasicNameValuePair("simCard", Devnum);
			params.add(number);
			params.add(type);
			params.add(eventType);
			params.add(simCard);
			logger.info("开始调用接口-------------*********");
			String result = BaseService.HttpPostWithUrlEncoder(url, params);
			logger.info("调用接口结束-------------*********");
			return result;
		}
}